import { controller, action, routeData } from "maishu-node-mvc";
import { getConfig, loadDatabaseConfig } from "../config";
import errors from "../errors";
import { Database } from "../database";

@controller("/")
export class HomeController {
    @action("/")
    async index() {
        return "database-service started";
    }

    @action("/alter/:file/:table")
    async alter(@routeData d: { table: string, file: string }) {
        if (!d.file) throw errors.argumentNull("file");
        if (!d.table) throw errors.argumentNull("table");

        d.table = d.table.toLowerCase();
        let databaseConfig = loadDatabaseConfig(d.file);
        let columnsConfig = databaseConfig.tables[d.table];
        if (!columnsConfig) throw errors.tableConfigNotFound(d.table, d.file);

        let config = getConfig();
        if (!config.conns[databaseConfig.conn])
            throw errors.connectionNotFound(databaseConfig.conn);

        let database = new Database(config.conns[databaseConfig.conn]);
        let tables = await database.getTableNames();
        if (!tables.includes(d.table)) {
            await database.createTable(d.table, columnsConfig);
        }
        else {
            await database.alterTable(d.table, columnsConfig);
        }

        return {};
    }
}